#ifndef _HEADER_VegetableGarden_H
#include "VegetableGarden.h"
#endif

#ifndef _HEADER_WaterSys_H
#include "WaterSys.h"
#endif

/**
 * 自动灌溉系统
 * */

//定义二块菜地
#define VEGETABLE_NUM 1
VegetableGarden vegetableGarden[VEGETABLE_NUM];
VegetableGardenConfig vegetableGardenConfig[VEGETABLE_NUM];

//供水系统
WaterSys waterSys;
WaterSysConfig waterSysConfig;

//全局输出缓存
char logStr[400]="";
//端口变量
int digPort = 3,analogPort = A0;

void setup()
{
    Serial.begin(9600);
    //初始化菜地
    for(int i=0;i<VEGETABLE_NUM;i++)
    {
        vegetableGardenConfig[i].gardenType = GardenTypeEnum::Cabbage;
        vegetableGardenConfig[i].humiditySensorPort = analogPort++;
        vegetableGardenConfig[i].waterSwitchPort = digPort++;
        vegetableGarden[i].init(&vegetableGardenConfig[i]);
        
        sprintf(logStr,"菜地%d初始化:",i);
        Serial.print(logStr);
        vegetableGarden[i].toString(logStr);
        Serial.println(logStr);
    }
    //最后一块菜地类型定义为萝卜
    vegetableGardenConfig[VEGETABLE_NUM-1].gardenType = GardenTypeEnum::Radish;
    
    //供水系统初始化
    waterSysConfig.waterTank0_outPump_port = digPort++;
    waterSysConfig.waterTank0_waterLine_port = analogPort++;
    waterSysConfig.waterTank0_waterSwitchIn_port = digPort++;
    waterSysConfig.waterTank0_waterSwitchOut_port = digPort++;
    waterSysConfig.waterTank1_outPump_port = digPort++;
    waterSysConfig.waterTank1_waterLine_port = analogPort++;
    waterSys.init(&waterSysConfig);
    waterSys.toString(logStr);
    Serial.println(logStr);
}

void loop() 
{

    //供水系统自动任务
    Serial.println("loop begin");
    bool isCloseWaterSys = true;
    waterSys.autoWork();
    /*
    if(waterSys.isReady() == false) 
    {
        Serial.println("自来水箱未满，继续加水中");
        goto __nextloop;
    }
    */

    //自动灌溉
    for(int i=0;i<VEGETABLE_NUM;i++)
    {
        vegetableGarden[i].isCanWatering();
        if(vegetableGarden[i].canWatering)
        {
            vegetableGarden[i].openWaterSwitch();
            waterSys.open();
            isCloseWaterSys = false;
            sprintf(logStr,"菜地%d正在灌溉中",i);
            Serial.println(logStr);
        }
        else
        {
            vegetableGarden[i].closeWaterSwitch();
            sprintf(logStr,"菜地%d停止灌溉",i);
            Serial.println(logStr);
        }
        //打印菜地
        vegetableGarden[i].toString(logStr);
        Serial.println(logStr);
    }

    //所有的菜地都未灌溉，关闭供水系统
    if(isCloseWaterSys == true)
    {
        waterSys.close();
        Serial.println("所有菜地都未灌溉，关闭供水系统。");
        goto __nextloop;
    }

    //水路添加剂
    
    __nextloop:
    //打印供水系统
    waterSys.toString(logStr);
    Serial.println(logStr);

    Serial.println("loop end");
    delay(3000);
}
